package me.sealer.ssm.exception.resolver;

import me.sealer.ssm.constant.Dict;
import me.sealer.ssm.constant.ErrorCodeConstant;
import me.sealer.ssm.core.Messageable;
import me.sealer.ssm.exception.SsmException;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 功能描述： $ SsmExceptionResolver
 *
 * @author sealer
 * @email 1178884049@qq.com
 * @date 2019年11月27日 10时07分54秒
 */
@Component
public class SsmHandlerExceptionResolver implements HandlerExceptionResolver, ApplicationContextAware {
    private ApplicationContext applicationContext;

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        SsmException ssmException;

        if (ex instanceof SsmException) {
            ssmException = (SsmException) ex;
        } else if (ex instanceof UnauthorizedException) {
            ssmException = new SsmException(ErrorCodeConstant.SYSTEM_NOT_AUTHORIZED);
        } else {
            ssmException = new SsmException(ex);
        }

        String returnCode = ssmException.getReturnCode();
        Messageable messageable = ssmException.getMessageable();

        String message = applicationContext.getMessage(messageable.getMessageKey(), messageable.getArgs(), messageable.getDefaultMessage(), request.getLocale());

        if (message == null || "".equals(message)) {
            message = messageable.getDefaultMessage();
        }

        Map exceptionResultMap = new HashMap(8);
        exceptionResultMap.put(Dict.RETURN_CODE, returnCode);
        exceptionResultMap.put(Dict.RETURN_MESSAGE, message);

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("error-500");
        modelAndView.addAllObjects(exceptionResultMap);
        return modelAndView;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;

    }
}
